import { SearchBar, Swiper, Toast, Badge, TabBar,Tabs  } from 'antd-mobile'
import '../home/home.css'
import { useRef, useEffect, useState } from 'react'
import { home,addCart } from '../../api/home'
import fire from "../../assets/fire.png"
import { useNavigate, useLocation } from 'react-router-dom'

// 添加购物车图标
import add from '../../assets/add.png'
// 添加成功图标
import ok from '../../assets/ok.png'


import {
  AppOutline,
  MessageOutline,
  MessageFill,
  UnorderedListOutline,
  UserOutline,
} from 'antd-mobile-icons'

let url='http://jingxun.kuxia.top'

export default function Home() {
  const navigate = useNavigate()
  const location = useLocation()
  
  const tabs = [
    {
      key: '/home',
      title: '首页',
      icon: <AppOutline />,
      badge: Badge.dot,
    },
    {
      key: '/fenlei',
      title: '分类',
      icon: <UnorderedListOutline />,
      badge: '5',
    },
    {
      key: '/shopping',
      title: '购物车',
      icon: (active) =>
        active ? <MessageFill /> : <MessageOutline />,
      badge: '99+',
    },
    {
      key: '/mine',
      title: '我的',
      icon: <UserOutline />,
    },
  ]

  const [activeKey, setActiveKey] = useState(location.pathname)

  const ref = useRef(null)
  const [iconData, setIconData] = useState([])
  const [bannerData, setBannerData] = useState([])
  const [hotData, setHotData] = useState([])
  const [classifyTitleData, setClassifyTitleData] = useState([])
  const [commodityData, setCommodityData] = useState([])
  // 添加购物车商品状态
  const [cartItems, setCartItems] = useState({})
  
  useEffect(() => {
    setActiveKey(location.pathname)
  }, [location.pathname])
  
  useEffect(() => {
    fetchHomeData()
  }, [])
  
  const fetchHomeData = async () => {
    try {
      const res = await home()
      console.log(res);
      
      // 获取分类图标数据
      if (res.data && res.data.classify) {
        setIconData(res.data.classify)
      }
      
      // 获取轮播图数据
      if (res.data && res.data.banner) {
        setBannerData(res.data.banner)
      }
      
      // 获取热门榜单数据
      if (res.data && res.data.hot) {
        setHotData(res.data.hot)
      }
      
      // 获取分类标题数据
      if (res.data && res.data.classify) {
        setClassifyTitleData(res.data.classify)
      }
      
      // 获取商品数据
      if (res.data && res.data.commodity) {
        setCommodityData(res.data.commodity)
      }
    } catch (error) {
      console.error('获取首页数据失败:', error)
      Toast.show({
        icon: 'fail',
        content: '获取数据失败',
        position: 'top'
      })
    }
  }

  const setRouteActive = (key) => {
    setActiveKey(key)
    navigate(key)
  }

  // 添加商品到购物车
  const handleAddToCart = async (commodityId) => {
    try {
      // 从本地存储获取用户信息
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
      const userId = userInfo.id;
      
      if (!userId) {
        Toast.show({
          content: '请先登录',
          position: 'top'
        });
        return;
      }
      
      // 调用添加购物车接口
      const response = await addCart({
        user_id: userId,
        commodity_id: commodityId,
        num: "1"
      });
      
      if (response.code === 1) {
        // 更新购物车状态
        setCartItems(prev => ({
          ...prev,
          [commodityId]: true
        }));
        
        Toast.show({
          content: '添加成功',
          position: 'top'
        });
      } else {
        Toast.show({
          content: '添加失败',
          position: 'top'
        });
      }
    } catch (error) {
      Toast.show({
        content: '添加失败',
        position: 'top'
      });
      console.error('添加购物车失败:', error);
    }
  };

  // 将商品数据分为两列
  const renderWaterfall = () => {
    const leftColumn = [];
    const rightColumn = [];
    
    commodityData.forEach((item, index) => {
      if (index % 2 === 0) {
        leftColumn.push(item);
      } else {
        rightColumn.push(item);
      }
    });
    
    return { leftColumn, rightColumn };
  };
  
  const { leftColumn, rightColumn } = renderWaterfall();

  return (
    <div style={{backgroundColor:'#F8F8F8', paddingBottom: '50px'}}>
      <div className='search-box'>
        <SearchBar
          placeholder='请输入内容'
          style={{ 
            '--background': '#ffffff',
            width: '90%',
            '--border-radius': '60px',
          }}
        />
        <div className='search-icon'>搜索</div>
      </div>

      {/* 轮播图 */}
      <div className='banner-box'>
        <Swiper
          loop
          autoplay
          style={{height: '160px'}}
        >
          {bannerData.map((item, index) => (
            <Swiper.Item key={index}>
              <div
                style={{ 
                  height: '100%',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: '24px',
                  fontWeight: 'bold'
                }}
                onClick={() => {
                  Toast.show(`你点击了卡片 ${index + 1}`)
                }}
              >
                <img 
                  src={url + item.banner} 
                  alt={item.title} 
                  style={{ 
                    width: '100%', 
                    height: '100%',
                    objectFit: 'cover'
                  }} 
                />
              </div>
            </Swiper.Item>
          ))}
        </Swiper>
      </div>

      {/* 图标 */}
      <div className='icon-box'>
        {iconData.map((item, index) => (
          <div key={index} className="icon-item">
            <img src={url+item.icon} alt={item.name} />
            {item.title && <span>{item.title}</span>}
          </div>
        ))} 
      </div>

      {/* 榜单 */}
      <div className='rank-box'>
        <div className='title'>
          <img src={fire} alt="" />
          <p>热门榜单</p>
          <div className='more'>更多</div>
        </div>
        <div className='rank-content'>
          <Swiper
            style={{ height: '200px' }}
            slideSize={34}
            loop={false}
          >
            {hotData.map((item, index) => (
              <Swiper.Item key={index}>
                <div className='rank-item'>
                  <img src={url + item.image} alt={item.title} />
                  <div className='rank-item-text'>
                    <p className='rank-item-title'>{item.title}</p>
                    <p className='rank-item-price'>¥{item.price}</p>
                  </div>
                </div>
              </Swiper.Item>
            ))}
          </Swiper>
        </div>

        {/* 猜你喜欢 */}
        <div className='guesslike-title'>
          <Tabs defaultActiveKey='1'>
            <Tabs.Tab title='猜你喜欢' key='1'>
            </Tabs.Tab>
            {classifyTitleData.map((item, index) => (
              <Tabs.Tab title={item.title} key={index + 2}>
              </Tabs.Tab>
            ))}
          </Tabs>
        </div>
        
         {/* 瀑布流商品列表 */}
        <div className="waterfall-container">
          <div className="waterfall-column">
            {leftColumn.map((item, index) => (
              <div 
                className="waterfall-item" 
                key={`left-${index}`}
                onClick={() => navigate(`/goods/${item.id}`)}
              >
                <img src={url + item.image} alt={item.title} />
                <p className="waterfall-item-title">{item.title}</p>
                <p className="waterfall-item-price">¥{item.price}</p>
                <img 
                  src={cartItems[item.id] ? ok : add} 
                  alt={cartItems[item.id] ? "已添加" : "添加到购物车"}
                  className="add-to-cart-icon"
                  style={{ width: '20px', height: '20px',position: 'absolute', right: '10px', bottom: '9px' }}
                  onClick={(e) => {
                    e.stopPropagation();
                    handleAddToCart(item.id);
                  }}
                />
              </div>
              
            ))}
          </div>
          <div className="waterfall-column">
            {rightColumn.map((item, index) => (
              <div 
                className="waterfall-item" 
                key={`right-${index}`}
                onClick={() => navigate(`/goods/${item.id}`)}
              >
                <img src={url + item.image} alt={item.title} />
                <p className="waterfall-item-title">{item.title}</p>
                <p className="waterfall-item-price">¥{item.price}</p>
                <img 
                  src={cartItems[item.id] ? ok : add} 
                  alt={cartItems[item.id] ? "已添加" : "添加到购物车"}
                  className="add-to-cart-icon"
                  style={{ width: '20px', height: '20px',position: 'absolute', right: '10px', bottom: '9px' }}
                  onClick={(e) => {
                    e.stopPropagation();
                    handleAddToCart(item.id);
                  }}
                />
              </div>
            ))}
          </div>
        </div>

      </div>

      {/* 底部导航栏 */}
      <div style={{ position: 'fixed', bottom: 0, width: '100%',backgroundColor:'#ffffff' }}>
        <TabBar activeKey={activeKey} onChange={setRouteActive}>
          {tabs.map(item => (
            <TabBar.Item key={item.key} icon={item.icon} title={item.title} />
          ))}
        </TabBar>
      </div>
    </div>
  )
}